<?php

namespace App\Admin\Actions\Merchant;

use App\Admin\Imports\Merchant;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use App\Admin\Imports\Customer;

class ImportMerchant extends Action
{
    public $name = '导入数据';

    protected $selector = '.import-merchant';

    public function handle(Request $request)
    {

        $import = new Merchant();

        $import->import($request->file('file'));

        $str = "";

        foreach ($import->failures() as $failure) {

            $str .=  ' 第'. $failure->row() . '行 失败原因：' . implode(' ', $failure->errors()) . '<br> 行数据：' . implode(' ', $failure->values()). '<br>';

        }

        if ($str !== '') {
            return $this->response()->success($str)->topFullWidth()->timeout(7000000);
        }

        return $this->response()->success('导入完成！')->refresh();
    }

    /**
     * 导入表单
     */
    public function form()
    {
        $this->file('file', '请选择文件')->help('数据量尽量不要超过1000条，如果超过1000条请分批导入！');
    }

    /**
     * 按钮
     */
    public function html()
    {
        return <<<HTML
        <div class="btn-group" style="margin-right: 5px;">
            <a class="btn btn-sm bg-purple hidden-xs"><span class="selected">导入数据</span></a>
            <btton type="button" class="btn btn-sm bg-purple" data-toggle="dropdown">
                <span class="caret"></span>
                <span class="sr-only">Toggle Dropdown</span>
            </btton>
            <ul class="dropdown-menu" role="menu">
                <li><a href="#" onclick="downloads()" class="grid-batch-1"><i class="fa fa-download"></i>下载导入模板 </a></li>
                <li><a href="#" class="grid-batch-2 import-merchant"><i class="fa fa-upload"></i>批量导入 </a></li>
            </ul>
    </div>
    <script >
        function downloads(){
           window.open("/admin/download/data/import?type=merchant")
        }
    </script>
HTML;
    }
}